﻿using System;
using System.Collections.Generic;
using System.Text;
using LitJson;

namespace TaiDouCommon.Tools
{
    public class ParameterTool
    {
        /// <summary>
        /// 解析参数，并转成指定的类型T
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="parameters">参数字典</param>
        /// <param name="code">参数类型</param>
        /// <param name="isRef">是否是引用类型</param>
        /// <returns></returns>
        public static T GetParameters<T>(Dictionary<byte, object> parameters, ParameterCode code, bool isRef=true)
        {
            object o = null;
            parameters.TryGetValue((byte) code, out o);

            //如果是引用类型，需要json强转
            if (isRef)
            {
                return JsonMapper.ToObject<T>(o.ToString());
            }

            return (T)o;
        }

        /// <summary>
        /// 向字典中添加参数
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="parameters">参数字典</param>
        /// <param name="key">参数类型</param>
        /// <param name="value">值对象</param>
        /// <param name="isRef">是否是引用类型</param>
        public static void AddParameters<T>(Dictionary<byte, object> parameters, ParameterCode key, T value, bool isRef = true)
        {
            if (isRef)
            {
                string json = JsonMapper.ToJson(value);
                parameters.Add((byte)key, json);
            }
            else {
                parameters.Add((byte)key, value);
            }
           
        }
    }
}
